<template>
  <el-dialog v-model="dialogUser" title="用户管理" width="80%">
    <div class="container">
      <div class="left">
        <!-- 添加按钮 -->
        <el-col>
          <el-button type="primary" :icon="CirclePlus" @click="handleAdd">添加</el-button>
        </el-col>
        <el-col>
          <el-button type="warning" @click="handleDel">批量删除</el-button>
        </el-col>
      </div>
      <!-- 搜索框+下拉框 -->
      <div class="right">
        <el-col>
          <el-input
            v-model="inputSearch"
            placeholder="请输入用户名搜索"
            class="input-with-select"
            style="width: 320px"
            :prefix-icon="Search"
            @change="handleSearch"
          >
          </el-input>
        </el-col>
      </div>
    </div>
    <!-- 表单数据 -->
    <el-table
      ref="multipleTableRef"
      :data="user"
      stripe
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column label="id" prop="use_id" sortable width="80px"></el-table-column>
      <el-table-column label="用户名" prop="user_username"></el-table-column>
      <el-table-column label="密码" prop="user_password"></el-table-column>
      <el-table-column label="用户类型" prop="user_type"></el-table-column>
      <el-table-column label="真实姓名" prop="use_truename"></el-table-column>
      <el-table-column label="手机号码" prop="user_tel"></el-table-column>
      <el-table-column label="用户在线状态" prop="user_onlinestatus">
        <template #default="scope">
          <el-switch
            v-model="scope.row.user_onlinestatus"
            active-value="已登录"
            inactive-value="未登录"
            active-color="#13ce66"
            inactive-color="#B9B9B9"
          />
        </template>
      </el-table-column>

      <!-- 删除 -->
      <el-table-column label="操作">
        <template #default="scope">
          <el-button
            size="small"
            type="danger"
            :icon="Delete"
            @click="handleDelete(scope.row.use_id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      :current-page="page"
      :page-size="size"
      :page-sizes="[1, 2, 5, 10]"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
    </el-pagination>
  </el-dialog>

  <!-- 对话框 -->
  <el-dialog title="添加用户" v-model="dialogVisible" width="40%">
    <el-form
      ref="userFormRef"
      :model="userForm"
      status-icon
      :rules="userRules"
      label-width="80px"
      @keyup.enter.native="handleSubmit"
    >
      <el-form-item label="用户名" prop="user_username">
        <el-input
          v-model="userForm.user_username"
          type="text"
          autocomplete="off"
          autofocus
        ></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="user_password">
        <el-input
          v-model="userForm.user_password"
          type="password"
          autocomplete="off"
          show-password
        ></el-input>
      </el-form-item>

      <el-form-item label="真实姓名" prop="use_truename">
        <el-input
          v-model="userForm.use_truename"
          type="text"
          autocomplete="off"
          autofocus
        ></el-input>
      </el-form-item>
      <el-form-item label="手机号码" prop="user_tel">
        <el-input
          v-model.number="userForm.user_tel"
          type="text"
          autocomplete="off"
          autofocus
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup>
import { ref, toRefs, getCurrentInstance } from 'vue'
import { useUserDialog } from '@/stores/dialogUser.js'
import { CirclePlus, Search, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox, ElTable } from 'element-plus'

const { dialogUser } = toRefs(useUserDialog())
const { proxy } = getCurrentInstance()
const inputSearch = ref('')
let user = ref([])
let total = ref(0)
const page = ref(1)
const size = ref(5)
const use_id = ref([])
const dialogVisible = ref(false)
const multipleTableRef = ref('')
const multipleSelection = ref(user.value)
const isEdit = ref(false) //true是修改，false是添加
//表单校验
const userForm = ref({
  user_username: '',
  user_password: '',
  use_truename: '',
  user_tel: ''
})
const userFormRef = ref('ruleFormRef')
const userRules = ref({
  user_username: [
    { required: true, message: '用户名不能为空', trigger: 'blur' },
    { min: 3, max: 7, message: '用户名长度为3-7个字符', trigger: 'blur' }
  ],
  user_password: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    { min: 3, max: 7, message: '密码长度为3-7个字符', trigger: 'blur' }
  ],
  use_truename: [
    { required: true, message: '真实姓名不能为空', trigger: 'blur' },
    { min: 2, max: 7, message: '用户名长度为2-7个字符', trigger: 'blur' }
  ],
  user_tel: [
    { required: true, message: '号码不能为空', trigger: 'blur' },
    { type: 'number', message: '必须为数字', trigger: 'blur' }
  ]
})
proxy.$http.get('/user', { params: { page: page.value, size: size.value } }).then((res) => {
  user.value = res.result.data
  total.value = res.result.total
})
// 分页
const handleCurrentChange = (p) => {
  page.value = p
  proxy.$http.get('/user', { params: { page: page.value, size: size.value } }).then((res) => {
    user.value = res.result.data
    total.value = res.result.total
  })
}
const handleSizeChange = (s) => {
  size.value = s
  proxy.$http.get('/user', { params: { page: page.value, size: size.value } }).then((res) => {
    user.value = res.result.data
    total.value = res.result.total
  })
}
// 提交表单
const handleSubmit = () => {
  // 1. 获取表单组件对象
  // 2. 调用validate方法
  userFormRef.value.validate((valid) => {
    if (valid) {
      // 发送请求 POST /users {username: xxx, password: xxx}
      proxy.$http.post('/user', userForm.value).then((res) => {
        // 1. 解构res
        const { code, message } = res
        if (code === 0) {
          // 1. 关闭对话框
          dialogVisible.value = false
          // 2. 提示成功
          ElMessage.success('添加成功')
          // 3. 重新的获取数据
          proxy.$http
            .get('/user', { params: { page: page.value, size: size.value } })
            .then((res) => {
              user.value = res.result.data
              total.value = res.result.total
            })
          // 4. 清空表单
          userFormRef.value.resetFields()
        } else {
          ElMessage.error(message)
        }
      })
    }
  })
}
// 添加用户
const handleAdd = () => {
  dialogVisible.value = true
  isEdit.value = false
}
// 批量删除
const handleSelectionChange = (val) => {
  multipleSelection.value = val
  multipleSelection.value.forEach((item) => {
    use_id.value.push(item.use_id)
  })
}
const handleDel = () => {
  const id = use_id.value
  ElMessageBox.confirm('删除后不可恢复，您确定要删除吗?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      proxy.$http.delete(`/user/${id}`).then((res) => {
        const { code, message } = res
        if (code == 0) {
          dialogVisible.value = false
          ElMessage.success('删除成功')
          proxy.$http
            .get('/user', { params: { page: page.value, size: size.value } })
            .then((res) => {
              user.value = res.result.data
              total.value = res.result.total
            })
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除'
      })
    })
}
// 删除单个
const handleDelete = (id) => {
  ElMessageBox.confirm('删除后不可恢复，您确定要删除吗?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      proxy.$http.delete(`/user/${id}`).then((res) => {
        const { code, message } = res
        if (code == 0) {
          dialogVisible.value = false
          ElMessage.success('删除成功')
          proxy.$http
            .get('/user', { params: { page: page.value, size: size.value } })
            .then((res) => {
              user.value = res.result.data
              total.value = res.result.total
            })
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除'
      })
    })
}

const handleReset = () => {
  if (!userFormRef.value) return
  userFormRef.value.resetFields()
}

const handleSearch = () => {
  proxy.$http
    .get('/user', {
      params: {
        page: page.value,
        size: size.value,
        keyword: inputSearch.value
      }
    })
    .then((res) => {
      user.value = res.result.data
      total.value = res.result.total
    })
}
</script>

<style scoped>
.container {
  display: flex;
  justify-content: space-between;
  /* align-items: start; */
  margin-bottom: 20px;
}
.container .left {
  width: 100px;
  display: flex;
}

.input-with-select .el-input-group__prepend {
  background-color: var(--el-fill-color-blank);
}
.el-pagination {
  margin-top: 20px;
}
</style>
